package com.cheney.demo.controller;

import com.cheney.demo.model.TestName;
import com.cheney.demo.model.TestUser;
import com.cheney.demo.service.TestNameService;
import com.cheney.demo.service.TestUserService;
import io.seata.spring.annotation.GlobalTransactional;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * @author si.chen
 * @date 2021/6/30 16:06
 */
@RestController
@RequestMapping("/seata")
public class SeataController {

    @Autowired
    private TestUserService testUserService;

    @Autowired
    private TestNameService testNameService;

    /**
     * 事务代码可以放在controller层，只要在@GlobalTransactional代码内就在同一个分布式事务
     */
    @GetMapping("/test")
    @GlobalTransactional
    public String test() {
        TestName testName = new TestName("name002");
        testNameService.save(testName);
        TestUser testUser = new TestUser("name002");
        testUserService.save(testUser);
        int i = 1 / 0;
        return "ok";
    }

    @GetMapping("/test2")
    @GlobalTransactional
    public String test2() {
        TestName testName = new TestName("name001");
        testNameService.save(testName);
        TestUser testUser = new TestUser("name001");
        testUserService.save(testUser);
        return "ok";
    }
}
